package com.kye.express.business.deposit.fragment;

import android.databinding.DataBindingUtil;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.NetworkMonitorUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.deposit.model.EventBusMsgModel;
import com.kye.express.business.deposit.presenter.DepositRechargeContract;
import com.kye.express.business.deposit.viewholder.DepositRechargeItemViewBinder;
import com.kye.express.databinding.FragmentDepositRechargeBinding;
import com.kye.express.view.ToastManager;
import com.kye.express.view.reclyerview.RecycleViewDivider;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.deposit.ResultShowPaymentRecordBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 预存运费-充值记录Fragment
 * <p>
 * Created by SkyYu on 2018/1/17
 */
public class DepositRechargeFragment extends BaseAppCompatFragment implements DepositRechargeContract.DepositRechargeView {

    private FragmentDepositRechargeBinding mBinding;
    private DepositRechargeContract.DepositRechargePresenter mPresenter;
    private MultiTypeAdapter mAdapter;

    private String phone;
    private int pageSize = Constants.PAGE_SIZE;
    public int mCurrentPageIndex = 1;

    public static DepositRechargeFragment newInstance() {
        return new DepositRechargeFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_deposit_recharge, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initData();
        initEvent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) {
            mPresenter.unbind();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initView(View view) {
        initBinding(view);
        initPresenter();
    }

    private void initBinding(View view) {
        mBinding = DataBindingUtil.bind(view);
    }

    private void initData() {
        mBinding.statusLayoutDepositRecharge.showLoadingView();
        initAdapter();
    }

    private void initPresenter() {
        mPresenter = new DepositRechargeContract.DepositRechargePresenter(this);
        mPresenter.bind(this);
    }

    private void initAdapter() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(ResultShowPaymentRecordBean.DatasBean.class, new DepositRechargeItemViewBinder());
        Items mDataItem = new Items();
        mAdapter.setItems(mDataItem);

        mBinding.recyclerviewDepositRecharge.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mBinding.recyclerviewDepositRecharge.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, 3, getResources().getColor(R.color.grey_d9d9d9)));
        mBinding.recyclerviewDepositRecharge.setItemAnimator(new DefaultItemAnimator());
        mBinding.recyclerviewDepositRecharge.setAdapter(mAdapter);
    }

    private void initEvent() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        mBinding.refreshLayoutDepositRecharge.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                request(false, false, false, phone, mCurrentPageIndex, pageSize);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                request(false, false, true, phone, mCurrentPageIndex, pageSize);
            }
        });

        RxView.clicks(mBinding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    Logger.d("onEmpty");
                    mBinding.statusLayoutDepositRecharge.showLoadingView();
                    request(false, false, false, phone, mCurrentPageIndex, pageSize);

                });
        RxView.clicks(mBinding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    Logger.d("onErrorNet");
                    mBinding.statusLayoutDepositRecharge.showLoadingView();
                    request(false, false, false, phone, mCurrentPageIndex, pageSize);
                });
        RxView.clicks(mBinding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    Logger.d("onErrorServer");
                    mBinding.statusLayoutDepositRecharge.showLoadingView();
                    request(false, false, false, phone, mCurrentPageIndex, pageSize);
                });
    }

    private void request(boolean isAutoLoading, boolean isFirstIn, boolean isLoadMore, String phone, int pageIndex, int pageSize) {
        NetworkMonitorUtils.networkObservable(getActivity())
                .map((connectivity) -> {
                    NetworkInfo.State state = connectivity.getState();
                    switch (state) {
                        case CONNECTED:
                        case CONNECTING:
                            return true;
                        case DISCONNECTED:
                        case DISCONNECTING:
                            return false;
                        default:
                            return false;
                    }
                })
                .subscribe((Boolean) -> {
                    if (Boolean) {
                        mPresenter.refreshData(isAutoLoading, isFirstIn, isLoadMore, phone, pageIndex, pageSize);
                    } else {
                        mBinding.statusLayoutDepositRecharge.showErrorNetworkView();
                        ToastManager.show(getActivity(), getString(R.string.common_net_error));
                    }
                });
    }

    @Subscribe
    public void onEventMainThread(EventBusMsgModel msg) {
        if (msg.getType() == EventBusMsgModel.TYPE_REFRESH) {
            onLoading();
        }
    }

    @Override
    public void onLoadUserData(User user) {
        phone = user.getPhone();
        request(false, true, false, phone, mCurrentPageIndex, pageSize);
    }

    @Override
    public void onLoading() {
        mBinding.refreshLayoutDepositRecharge.autoRefresh();
    }

    @Override
    public void onComplete(boolean isLoadMore) {
        if (isLoadMore) {
            mBinding.refreshLayoutDepositRecharge.finishLoadmore();
        } else {
            mBinding.refreshLayoutDepositRecharge.finishRefresh();
        }
    }

    @Override
    public void onSuccessLoadData(OpenApiResult<ResultShowPaymentRecordBean> bean, boolean isFirstIn, boolean isLoadMore) {
        if (bean != null) {
            if (bean.getCode() == Constants.ResponseCode_SUCCESS) {
                if (bean.getData().getDatas().size() > 0) {
                    mBinding.statusLayoutDepositRecharge.showContentView();
                    @SuppressWarnings("unchecked")
                    List<ResultShowPaymentRecordBean.DatasBean> data = (List<ResultShowPaymentRecordBean.DatasBean>) mAdapter.getItems();
                    if (!isLoadMore) {
                        data.clear();
                        data.addAll(bean.getData().getDatas());
                        mAdapter.notifyDataSetChanged();
                    } else {
                        data.addAll(bean.getData().getDatas());
                        int start = bean.getData().getDatas().size();
                        mAdapter.notifyItemRangeChanged(start, data.size());
                    }
                } else {
                    if (isFirstIn) {
                        ToastManager.show(getActivity(), getString(R.string.common_no_more_datas));
                        mBinding.statusLayoutDepositRecharge.showEmptyView();
                    } else {
                        ToastManager.show(getActivity(), getString(R.string.common_no_more_datas));
                    }
                }
                if(bean.getData().getDatas().size() < pageSize){
                    mBinding.refreshLayoutDepositRecharge.setEnableLoadmore(false);
                }
            } else {
                if (isLoadMore) {
                    ToastManager.show(getActivity(), getString(R.string.common_no_more_datas));
                } else {
                    ToastManager.show(getActivity(), bean.getMsg());
                }
            }
        } else {
            Logger.d("DepositRechargeFragment - onSuccessLoadData - bean is null");
        }
    }

    @Override
    public void onApiError(OpenApiResult<ResultShowPaymentRecordBean> result, int code, String msg) {
        mBinding.statusLayoutDepositRecharge.showErrorServerView();
        ToastManager.show(getActivity(), msg);
        Logger.d("DepositRechargeFragment - onApiError - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void onOtherError(Throwable e) {
        mBinding.statusLayoutDepositRecharge.showErrorNetworkView();
        ToastManager.show(getActivity(), getString(R.string.common_net_error));
        Logger.d("DepositRechargeFragment - onOtherError : " + e.getMessage());
        e.printStackTrace();
    }
}